package com.schoolhelper.utils;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.schoolhelper.SHApplication;
import com.schoolhelper.controller.activity.BuildConfig;
import com.schoolhelper.model.YyzExecutors;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import lombok.SneakyThrows;

import static android.os.FileUtils.copy;

public class ImageUtils {

    public final static int IO_BUFFER_SIZE = 1024 * 2;

    /**
     * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
     * <p>
     * A.网络路径: url=&quot;http://blog.foreverlove.us/girl2.png&quot; ;
     * <p>
     * B.本地路径:url=&quot;file://mnt/sdcard/photo/image.png&quot;;
     * <p>
     * C.支持的图片格式 ,png, jpg,bmp,gif等等
     *
     * @param url 图像地址
     * @return Bitmap
     */
    @SneakyThrows
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static Bitmap GetLocalOrNetBitmap(String url) {
        if (url == null) {
            return null;
        }
        // 获取全局
        Context globalApplication = SHApplication.getGlobalApplication();
        Bitmap bitmap = null;
        // 去缓存里看看有没有图片的缓存
        String bitMapStr = MyCache.read(globalApplication, url);
        if (bitMapStr == null) {
            Future<Bitmap> future = YyzExecutors.submit(new Callable<Bitmap>() {
                @Override
                public Bitmap call() throws Exception {
                    Bitmap bitmap = null;
                    InputStream in = null;
                    BufferedOutputStream out = null;
                    in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
                    copy(in, out);
                    out.flush();
                    byte[] data = dataStream.toByteArray();
                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                    System.out.println(Arrays.toString(data));
                    return bitmap;
                }
            });
            bitmap = future.get();
            // 转base64
            String str = bitmap2String(bitmap, 50);
            // 写入缓存
            MyCache.write(globalApplication, url, str);
        } else {
            bitmap = string2Bitmap(bitMapStr);
        }

        return bitmap;


    }

    @SneakyThrows
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static Bitmap GetLocalOrNetBitmap(String url, Context context) {
        Bitmap bitmap = null;
        // 去缓存里看看有没有图片的缓存
        String bitMapStr = MyCache.read(context, url);
        if (bitMapStr == null) {
            bitmap = GetLocalOrNetBitmap(url);
            // 转base64
            String str = bitmap2String(bitmap, 50);
            // 写入缓存
            MyCache.write(context, url, str);
        } else {
            bitmap = string2Bitmap(bitMapStr);
        }

        return bitmap;
    }

    /**
     * 将bitmap转换成base64字符串
     *
     * @param bitmap
     * @return base64 字符串
     */
    public static String bitmap2String(Bitmap bitmap, int bitmapQuality) {
        // 将Bitmap转换成字符串
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, bitmapQuality, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    /**
     * 将base64转换成bitmap图片
     *
     * @param string base64字符串
     * @return bitmap
     */
    public static Bitmap string2Bitmap(String string) {
        // 将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private static String TAG = "Test";
    public static File tempFile;

    public static Uri getImageUri(Context content) {
        File file = setTempFile(content);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            //将File对象转换成封装过的Uri对象，这个Uri对象标志着照片的真实路径
            Uri imageUri = FileProvider.getUriForFile(content, BuildConfig.APPLICATION_ID + ".provider", file);
            return imageUri;
        } else {
            //将File对象转换成Uri对象，这个Uri对象标志着照片的真实路径
            Uri imageUri = Uri.fromFile(file);
            return imageUri;
        }
    }

    public static File setTempFile(Context content) {
        //自定义图片名称
        String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".png";
        Log.i(TAG, " name : " + name);
        //定义图片存放的位置
        tempFile = new File(content.getExternalCacheDir(), name);
        Log.i(TAG, " tempFile : " + tempFile);
        return tempFile;
    }

    public static File getTempFile() {
        return tempFile;
    }
}
